﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace ReadWriteIsolate.DB
{
    public class SqlConnectionStringPool
    {
        private static string WriteString;
        private static string[] ReadStringMilti;
        private static int[] Score; //权重比例
        private static List<string> ReadStringMutiWithScore = new List<string>(); //带权重的数组

        static SqlConnectionStringPool()
        {
            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            WriteString = configuration.GetConnectionString("Write");
            ReadStringMilti = configuration.GetConnectionString("Read").Split('|');
            Score = configuration.GetSection("Weight").Value.Split('|').Select((s => Convert.ToInt32(s))).ToArray();
            //填充权重数组
            int index = 0;
            foreach (var score in Score)
            {
                for (int i = 0; i < score; i++)
                {
                    ReadStringMutiWithScore.Add(ReadStringMilti[index]);
                }
                index++;
            }

        }

        public static string GetConnectionString(ConnectionType connectionType)
        {
            switch (connectionType)
            {
                case ConnectionType.Read:
                    return Dispatch();
                case ConnectionType.Write:
                    return WriteString;
            }
            return string.Empty;
        }

        private static byte inum;

        ///// <summary>
        ///// 负载均衡 自定义策略 轮询策略
        ///// </summary>
        //private static string Dispatch()
        //{
        //    string connStr=ReadStringMilti[inum++ % ReadStringMilti.Length];
        //    if (inum==3)
        //    {
        //        inum = 0;
        //    }
        //    return connStr;
        //}

        /// <summary>
        /// 负载均衡 自定义策略 权重策略:每个数据库得有个权重,这个权重值去不平均分配
        /// 6:3:1
        /// </summary>
        private static string Dispatch()
        {
            //这里使用随机数就是为了平均,权重数组中的10个字符串拿到每个的概率是一样的
            return ReadStringMutiWithScore[new Random(inum++).Next(0, ReadStringMutiWithScore.Count)];
        }

        public enum ConnectionType
        {
            Read,
            Write,
        }

    }
}
